package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.clients.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.common.utils.UserHolder;
import com.hmall.order.dto.OrderDTO;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.hmall.common.constants.MqConstants.*;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderLogisticsService orderLogisticsService;

    @Transactional
    @Override
    public Long saveOrder(OrderDTO orderDTO) {
        //1、创建订单
        Order order = new Order();
        Item item = itemClient.getById(orderDTO.getItemId());
        order.setTotalFee(item.getPrice() * orderDTO.getNum());
        order.setPaymentType(orderDTO.getPaymentType());
        order.setUserId(UserHolder.getUser());
        order.setStatus(1); //未付款
        this.save(order);

        //2、创建订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(orderDTO.getItemId());
        orderDetail.setNum(orderDTO.getNum());
        orderDetail.setTitle(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setImage(item.getImage());
        this.orderDetailService.save(orderDetail);

        //3、创建订单物流信息
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        Address address = userClient.findAddressById(orderDTO.getAddressId());
        BeanUtils.copyProperties(address,orderLogistics,"","","");
        this.orderLogisticsService.save(orderLogistics);
//        orderDetailService.save();
        // 扣减库存
        try {
            itemClient.updateStockById(item.getId(),"deduct",orderDTO.getNum());
        } catch (Exception e) {
            System.err.println(e);
            throw new RuntimeException("库存不足");
        }

        Map<String,Object> messageMap = new HashMap<>();
        messageMap.put("orderId",order.getId());
        messageMap.put("userId",UserHolder.getUser());

        //5、发延时消息(ttl + 死信队列 机制)
        rabbitTemplate.convertAndSend(HMALL_TTL_DIRECT, HMALL_TTL_KEY, messageMap, message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            //设置消息存活时间为10秒
            messageProperties.setExpiration("10000");
            return message;
        });
        return order.getId();
    }
}
